package com.lzd.framework.springsecurity.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.lzd.framework.springsecurity.dao.SysUserMapper;
import com.lzd.framework.springsecurity.model.SysUser;
import com.lzd.framework.springsecurity.security.Oauth2User;
import com.lzd.framework.springsecurity.service.MyUserDetailsService;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class MyUserDetailsServiceImpl implements MyUserDetailsService{
	@Autowired
	private SysUserMapper sysUserMapper;
	
	public void insertUserIfNecessary(Oauth2User user) {
		log.info("----------insertUserIfNecessary----------");
	}

	@Override
	public Oauth2User loadUserByUsername(String username) throws UsernameNotFoundException {
		log.info("----------loadUserByUsername----------");		
		return getUserDetails(username);
	}
	
	private Oauth2User getUserDetails(String username) {
		SysUser sysUser = sysUserMapper.selectByUsername(username);

		if (sysUser == null) {
			throw new UsernameNotFoundException("用户不存在");
		}

		Collection<? extends GrantedAuthority> authorities
				= AuthorityUtils.createAuthorityList(getUserPermissions(sysUser.getUserId()).toArray(new String[0]));
		// 构造security用户
		return new Oauth2User(sysUser.getUserId(), sysUser.getUsername(), sysUser.getPassword(),authorities);
	}
	
	private Set<String> getUserPermissions(Long userId) {
		List<String> permsList=new ArrayList<String>();
		permsList.add(new String("admin:user:info"));		
		permsList.add(new String("admin:user:list"));
		permsList.add(new String("admin:user:del"));
		permsList.add(new String("admin:user:passwordencoder"));
		
		Set<String> permsSet = permsList.stream().flatMap((perms)->{
			if (StrUtil.isBlank(perms)) {
				return null;
			}
			return Arrays.stream(perms.trim().split(","));
		}
        ).collect(Collectors.toSet());
        return permsSet;		
	}
}
